﻿
(function () {
    'use strict';

    var controllerId = 'imageCtrl';
    angular.module('app').controller(controllerId,
        ['$scope', 'signalRConnection', 'imageSvc', '$rootScope', imageCtrl]);

    function imageCtrl($scope, signalRConnection, imageSvc, $rootScope) {
        $scope.title = "Images";

        $rootScope.$watch(function() {
            return imageSvc.images;
        }, function (newVal) {
            var image = _.last(newVal);

            if (newVal.length == 0) {
                return;
            }

            var newImage = '<img  alt="Embedded Image" width="100" height="80" src="data:image/png;base64,' + image.ImageBytes + '" />';


            console.log(newImage);
            $("#images").append("<li>"+ newImage +"</li>");//.append(currentImage);
            console.log(image);
           // $scope.imageList = newVal;
            //$scope.imageList = newVal;


        }, true);

        var number = 0;
        $scope.number = number;

        $scope.increaseNumber = function() {
            number++;
            $scope.number = number;
        };


        signalRConnection.connect();
        imageSvc.loadImages();

        $scope.uploadImages = function (e) {
            console.log("in uploader");
            var inputValue = $("#input").val();

            var onImageChangedSucces = function () {
                $("#result").html("<p>Image Uploaded</p>");
            };

            var onImageChangedError = function () {
                $("#result").html("<p>Error While Uploading Image</p>");
            };

            var input = $('form')[0];
            var formData = new FormData(input);

            $.ajax({
                url: "http://localhost:2664/api/ImageUpload/upload-image",
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false
            }).done(onImageChangedSucces)
              .error(onImageChangedError);
            return false;
        };

       
    }
})();
